<template>
  <div>
    <a-modal :title="currTitle()" :visible="visible" @cancel="showModel(false)">
      <template>
        <div class="table-operator" style="width: 20%; min-width: 400px">
          <a-form :form="form" @submit="handleSubmit">
            <!--        最大连接数-->
            <a-form-item v-bind="formItemLayout" label="同时登录数量限制">
              <a-input
                v-decorator="[`loginAtTheSameTime`, validatorRules.count]"
                placeholder="请输入 1 到 100 的整数"
                style="width: 80%; margin-right: 8px"
              />
            </a-form-item>
            <!--        启用IP绑定按钮-->
            <a-form-item v-bind="formItemLayout" label="启用IP绑定">
              <a-switch
                v-decorator="[
                  `loginIpWhiteListOnOff`,
                  {
                    // 绑定子节点的属性值
                    valuePropName: 'checked',
                    // 给子节点一个默认值
                    initialValue: true,
                  },
                ]"
                checked-children="开"
                un-checked-children="关"
                @click="btnClicked"
              />
            </a-form-item>
            <!-- 禁用时间段 -->
            <div v-if="btnChecked">
              <a-col :md="24" :sm="24">
                <a-form-item
                  label="开始禁用时间:"
                  :labelCol="{ span: 8 }"
                  :wrapperCol="{ span: 9, offset: 0 }"
                >
                  <a-date-picker
                    v-decorator="['limitTheLoginStartTime']"
                    :disabled-date="disabledStartDate"
                    show-time
                    :allowClear="false"
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择开始禁用时间"
                    @openChange="handleStartOpenChange"
                  />
                </a-form-item>
              </a-col>

              <a-col :md="24" :sm="24">
                <a-form-item
                  label="结束禁用时间:"
                  :labelCol="{ span: 8 }"
                  :wrapperCol="{ span: 9, offset: 0 }"
                >
                  <a-date-picker
                    v-decorator="['limitTheLoginEndTime']"
                    :disabled-date="disabledEndDate"
                    show-time
                    :allowClear="false"
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择结束禁用时间"
                    @openChange="handleEndOpenChange"
                  />
                </a-form-item>
              </a-col>
            </div>
            <!--        IP地址输入列表-->
            <div v-if="btnChecked">
              <a-form-item
                v-for="(k, index) in form.getFieldValue('keys')"
                :key="k"
                v-bind="
                  index === 0 ? formItemLayout : formItemLayoutWithOutLabel
                "
                :label="index === 0 ? 'IP地址绑定' : ''"
                :required="false"
              >
                <a-input
                  v-decorator="[`loginIpWhiteList[${k}]`, validatorRules.ip]"
                  placeholder="请输入需要绑定的IP地址"
                  style="width: 80%; margin-right: 8px"
                />
                <a-icon
                  class="dynamic-delete-button"
                  type="minus-circle-o"
                  @click="() => remove(k)"
                />
              </a-form-item>
              <a-form-item v-bind="formItemLayoutWithOutLabel">
                <a-button type="dashed" style="width: 80%" @click="add">
                  <a-icon type="plus" /> 添加绑定输入项
                </a-button>
              </a-form-item>
            </div>

            <!--            <a-form-item v-bind="formItemLayoutWithOutLabel">-->
            <!--              <a-button type="primary" html-type="submit">-->
            <!--                提交-->
            <!--              </a-button>-->
            <!--            </a-form-item>-->
          </a-form>
        </div>
      </template>
      <template slot="footer">
        <a-button type="primary" html-type="submit" @click="handleSubmit"
          >提交</a-button
        >
        <a-button @click="showModel(false)">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { getAction, postAction } from "@/api/manage";
import moment from "moment";

let id = 0;
export default {
  name: "UserLoginConfigModal",
  data() {
    return {
      startValue: "",
      endValue: "",
      userName: "",
      userID: "",
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 16, offset: 8 },
        },
      },
      validatorRules: {
        count: {
          validateTrigger: ["change", "blur"],
          rules: [
            {
              required: true,
              whitespace: true,
              pattern: /^([1-9][0-9]{0,1}|100)$/,
              message: "请输入1-100的整数!",
            },
          ],
        },
        ip: {
          validateTrigger: ["change", "blur"],
          rules: [
            {
              required: true,
              whitespace: true,
              // pattern:/^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/,
              pattern:
                /^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/,
              message: "请输入正确的IP地址 或 删除此项!",
            },
          ],
        },
      },
      btnChecked: true,
      ipList: [],
      url: {
        getParam: "/sys/user/user-login-config",
        setParam: "/sys/user/save-login-config",
      },
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "sys_param_set" });
    this.form.getFieldDecorator("keys", { initialValue: [], preserve: true });
  },
  mounted() {
    console.log("---------------------------------------");
  },
  methods: {
    currTitle() {
      let str = "[ " + this.userName + " ]的登录配置";
      return str;
    },
    showModel(visible) {
      this.visible = visible;
      if (this.userID.length !== 0) {
        this.getData();
      }
    },
    getData() {
      this.clearViewData();
      let that = this;
      getAction(that.url.getParam + "/" + this.userID).then((res) => {
        if (res.code === "00000") {
          console.log(res, "url.getParam");
          for (let i = 0; i < res.data.loginIpWhiteList.length; i++) {
            this.add();
          }
          this.btnChecked = true;
          if (res.data.loginIpWhiteListOnOff === "off") {
            this.btnChecked = false;
          }
          this.form.setFieldsValue({
            loginAtTheSameTime: res.data.loginAtTheSameTime,
            loginIpWhiteListOnOff: this.btnChecked,
          });
          that.ipList = res.data.loginIpWhiteList;

          // 判断 开始/结束 时间是否为空
          if (
            res.data.limitTheLoginStartTime == "null" ||
            res.data.limitTheLoginStartTime == "Invalid date"
          ) {
            that.startTime = null;
          } else {
            that.startTime = res.data.limitTheLoginStartTime;
          }

          if (
            res.data.limitTheLoginEndTime == "null" ||
            res.data.limitTheLoginEndTime == "Invalid date"
          ) {
            that.endTime = null;
          } else {
            that.endTime = res.data.limitTheLoginEndTime;
          }

          if (this.btnChecked) {
            this.$nextTick(() => {
              this.form.setFieldsValue({
                loginIpWhiteList: that.ipList,
                limitTheLoginStartTime: that.startTime,
                limitTheLoginEndTime: that.endTime,
              });
            });
          }
        } else {
          that.$message.warning("获取系统参数:" + res.msg);
          that.ipList = [];
          that.startTime = "";
        }
      });
    },
    setUserID(userid, username) {
      this.userID = userid;
      this.userName = username;
    },
    remove(k) {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue("keys");

      // can use data-binding to set
      form.setFieldsValue({
        keys: keys.filter((key) => key !== k),
      });
    },

    clearViewData() {
      id = 0;
      this.form.setFieldsValue({
        keys: [],
        loginIpWhiteList: [],
      });
    },
    add() {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue("keys");
      const nextKeys = keys.concat(id++);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });
    },

    // 开始结束时间
    disabledStartDate(startValue) {
      console.log(startValue);
      // return startValue && startValue < moment().subtract(1,'days').endOf("day");
    },
    disabledEndDate(endValue) {
      console.log(endValue);
    },

    handleSubmit() {
      let that = this;
      this.form.validateFields((err, values) => {
        if (!err) {
          // const { keys, names } = values;
          console.log("Received values of form: ", values);
          if (values.keys) {
            delete values.keys;
          }
          if (!("loginIpWhiteList" in values)) {
            values.loginIpWhiteList = this.ipList;
          }
          values.loginAtTheSameTime = Number(values.loginAtTheSameTime);
          values.loginIpWhiteListOnOff = that.btnChecked ? "on" : "off";
          values.userId = this.userID;

          // 判断是否开启ip绑定
          if (values.loginIpWhiteListOnOff == "on") {
            // 开始、结束时间格式转换以及判断
            if (values.limitTheLoginEndTime == null) {
              values.limitTheLoginEndTime = null;
            } else {
              values.limitTheLoginEndTime = moment(
                values.limitTheLoginEndTime
              ).format("YYYY-MM-DD HH:mm:ss");
            }

            if (values.limitTheLoginStartTime == null) {
              values.limitTheLoginStartTime = null;
            } else {
              values.limitTheLoginStartTime = moment(
                values.limitTheLoginStartTime
              ).format("YYYY-MM-DD HH:mm:ss");
            }

            // 开始 与 结束 时间都为空时
            if (
              values.limitTheLoginEndTime == null &&
              values.limitTheLoginStartTime == null
            ) {
              this.$message.warning("请选择禁用开始或者结束时间");
              return;
            } else if (
              values.limitTheLoginEndTime !== null &&
              values.limitTheLoginStartTime !== null
            ) {
              //开始 结束 时间判断
              let startValueTime = values.limitTheLoginStartTime;
              let endValueTime = values.limitTheLoginEndTime;
              console.log(startValueTime, endValueTime, "开始时间结束时间");
              let start = startValueTime.replace(/-/g, "");
              let starts = start.replace(/:/g, "");
              let startes = starts.replace(/ /g, "");
              console.log(startes);
              let end = endValueTime.replace(/-/g, "");
              let ends = end.replace(/:/g, "");
              let endes = ends.replace(/ /g, "");
              console.log(endes);

              if (startes > endes) {
                this.$message.warning("开始时间应早于结束时间！");
                return;
              }
      
            }
          }

          console.log("values of form: ", values);
          postAction(this.url.setParam, values).then((res) => {
            if (res.code == "00000") {
              that.$message.success("系统参数设置成功");
              that.ipList = values.loginIpWhiteList;
            } else {
              that.$message.warning("系统参数设置失败:" + res.msg);
            }
          });
        }
      });
    },

    validateIp() {
      return false;
    },
    btnClicked(checked) {
      this.btnChecked = checked;
      if (this.btnChecked) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            loginIpWhiteList: this.ipList,
            limitTheLoginStartTime: this.startTime,
            limitTheLoginEndTime: this.endTime,
          });
        });
      }
    },
  },
};
</script>
<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>